package com.example.droolstool.service;

import com.example.droolstool.base.Constants;
import com.example.droolstool.module.DrlMessageModule;
import com.example.droolstool.module.EdgeModule;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.drools.core.impl.InternalKnowledgeBase;
import org.drools.core.impl.KnowledgeBaseFactory;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieSession;
import org.kie.internal.builder.KnowledgeBuilder;
import org.kie.internal.builder.KnowledgeBuilderError;
import org.kie.internal.builder.KnowledgeBuilderErrors;
import org.kie.internal.builder.KnowledgeBuilderFactory;
import org.kie.internal.io.ResourceFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.EventListener;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author 赵云龙
 * @Date 2020/6/27
 * @Description TODO
 */

@Service
public class ServerAssembleDrlListener implements EventListener {

    public void ServerAssembleDrl(DrlMessageModule drlMessageModule){
        drlMessageModule.setExecuted(true);
        if (!StringUtils.equals("2",drlMessageModule.getType())) {
            String currentId = drlMessageModule.getId();
            System.out.println("this is " + drlMessageModule.getId() + "运行结束");
            executeDbConversion(drlMessageModule);
        } else {
            String currentId = ((EdgeModule)drlMessageModule).getSource();
            Constants.executedRuleId.add(currentId);
            Constants.executedDrlResultParams.put(currentId, drlMessageModule.getRespondParams());
            String toId = ((EdgeModule)drlMessageModule).getTarget();
            // todo 动态执行规则

            String rules= (String) Constants.drlMap.values().toArray()[0];
            KnowledgeBuilder builder = KnowledgeBuilderFactory.newKnowledgeBuilder();
            //以DRL形式加载规则
            builder.add(ResourceFactory.newByteArrayResource(rules.getBytes()), ResourceType.DRL);
            KnowledgeBuilderErrors errors = builder.getErrors();
//        Results results = builder.getResults();
//        if (results.hasMessages(org.kie.api.builder.Message.Level.ERROR)) {
//            System.out.println(results.getMessages());
//            throw new IllegalStateException("### errors ###");
//        }
            for (KnowledgeBuilderError error : errors) {
                System.out.println(error.getMessage());
            }
            InternalKnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase();
            kBase.addPackages(builder.getKnowledgePackages());
            //获取规则引擎会话session
            KieSession session = kBase.newKieSession();
            session.setGlobal("executedDrlIds", Lists.newArrayList(Constants.executedRuleId));
            session.setGlobal("endNoteId", Constants.endExecuteDrlIds);
            // todo    节点可以存储成一个缓存/数据库  这样不需要每次遍历原始数据
                Constants.serverAssembleModule.getServiceNodeModules().forEach(serverNodeModule -> {
                    if (StringUtils.equals(toId, serverNodeModule.getId())){
                        //插入需匹配的对象
                        serverNodeModule.setRequestParams(drlMessageModule.getRespondParams());
                        session.insert(serverNodeModule);
                        //执行规则
                        session.fireAllRules();
                        //释放资源
                        session.dispose();
                    }
                });
        }
    }

    /**
     * 执行数据转换服务调度
     * 存在不配置数据转换的
     * @param drlMessageModule
     */
    public void executeDbConversion(DrlMessageModule drlMessageModule){

        String currentId = drlMessageModule.getId();
        List<String> toId = drlMessageModule.getToId();
        if (!StringUtils.isEmpty(currentId) && toId != null && !CollectionUtils.isEmpty(toId)) {
            List<EdgeModule> edgeModules = Constants.serverAssembleModule.getEdgeModules();
            List<EdgeModule> executeEdgeModules = edgeModules.stream().filter(edgeModule ->
               edgeModule.getRequestParams()!= null && StringUtils.equals(currentId, edgeModule.getSource()) && toId.contains(edgeModule.getTarget())).collect(Collectors.toList());
            executeEdgeModules.forEach(edgeModule -> {
                edgeModule.setRequestParams(drlMessageModule.getRespondParams());
                //TODO  调度数据转换服务
                edgeModule.setRespondParams(drlMessageModule.getRespondParams());
                ServerAssembleDrl(edgeModule);
                System.out.println("this is " + edgeModule.getId() + "的数据转换");
            });

            List<EdgeModule> executeEdgeModulesNoConfig = edgeModules.stream().filter(edgeModule ->
                    edgeModule.getRequestParams()== null && StringUtils.equals(currentId, edgeModule.getSource()) && toId.contains(edgeModule.getTarget())).collect(Collectors.toList());
            executeEdgeModulesNoConfig.forEach(edgeModule -> {
                Constants.executedDrlResultParams.put(currentId, drlMessageModule.getRespondParams());

                edgeModule.setRespondParams(drlMessageModule.getRespondParams());
                ServerAssembleDrl(edgeModule);
                System.out.println("this is " + edgeModule.getId() + "的数据转换");
            });
        }
    }

}
